package com.example.alarm.mvvm.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.media.MediaPlayer.OnCompletionListener
import android.media.MediaPlayer.OnPreparedListener
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.widget.Toolbar
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.example.alarm.R
import com.example.alarm.mvvm.bean.AlarmDetailBean
import com.gsafety.library.BaseApplication
import com.gsafety.libraryktx.base.BaseActivity
import com.gsafety.libraryktx.config.Constant
import com.gsafety.libraryktx.util.GlideUtils
import kotlinx.android.synthetic.main.alarm_preview_image_layout.*
import java.io.File
import java.io.Serializable

/**
 * @author : lianbing.geng
 * @date : 2020/8/8 18:33
 */
class PreviewImageActivity : BaseActivity() {
    var imageViews: ArrayList<View> = ArrayList<View>()
    var mAdapter: MyPagerAdapter? = null
    var titleBar:TextView? = null
    var tv_right:TextView? = null
    var toolbar:Toolbar?= null
    override fun initView() {
        titleBar = findViewById<TextView>(R.id.title_name)
        tv_right = findViewById<TextView>(R.id.tv_right)
        tv_right?.visibility = View.VISIBLE
        toolbar = findViewById<Toolbar>(R.id.toolbar)
        vp_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                var bean = mAdapter?.dataLs?.get(position)
                bean.let {
                    var url = it?.urlAddr.toString()
                    if(url.substring(url.lastIndexOf(".")+1) == "mp4"){
                       if(mAdapter?.mVideoView!=null &&mAdapter?.mVideoView?.isPlaying!!){
                           mAdapter?.mVideoView?.pause()
                           mAdapter?.mBtnVideo?.visibility = View.VISIBLE
                       }
                    }
                }
            }

            override fun onPageSelected(position: Int) {
                titleBar?.text = mAdapter?.dataLs?.get(position)?.fileName
                var total = mAdapter?.dataLs?.size
                var pos = position + 1
                tv_right?.text = "($pos/$total)"
            }

        })
        var curIndex = intent.getIntExtra("current", 0)
        mAdapter = MyPagerAdapter()
        vp_pager.adapter = mAdapter
        mAdapter?.dataLs = intent.getSerializableExtra("imageList") as ArrayList<AlarmDetailBean.DocsBean>
        for(item in mAdapter?.dataLs!!){
            imageViews.add(
                LayoutInflater.from(this).inflate(
                    R.layout.alarm_image_preview_view,
                    null
                )
            )
        }
        mAdapter?.imageViews = imageViews
        vp_pager.setCurrentItem(curIndex, false)
        mAdapter?.notifyDataSetChanged()
        vp_pager.setOnClickListener {
            mAdapter?.mVideoView?.stopPlayback()
        }
        var total = mAdapter?.dataLs?.size
        tv_right?.text = "(1/$total)"
        titleBar?.text = mAdapter?.dataLs?.get(0)?.fileName
    }

    override fun initData() {

    }

    companion object {

        fun startIntent(ctx: Activity, data: List<AlarmDetailBean.DocsBean>?, curIndex: Int) {
            val intent = Intent()
            intent.putExtra("current", curIndex)
            intent.putExtra("imageList", data as Serializable)
            intent.setClass(ctx, PreviewImageActivity::class.java)
            ctx.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.alarm_preview_image_layout
    }

    class MyPagerAdapter : PagerAdapter() {
        var dataLs: ArrayList<AlarmDetailBean.DocsBean>? = null
        var imageViews: ArrayList<View>? = null
        var mVideoView:VideoView? = null
        var mBtnVideo:ImageView?=null
        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            var view = LayoutInflater.from(container.context).inflate(
                R.layout.alarm_image_preview_view,
                container,
                false
            )
            container.addView(view)
            var imageView:ImageView? = view?.findViewById(R.id.iv_image)
            var iv_video:ImageView? = view?.findViewById(R.id.iv_video)
            var video_view:VideoView? = view?.findViewById(R.id.video_view)
            imageView?.setOnClickListener {
                mVideoView?.stopPlayback()
                (container.context as Activity).finish()
            }
            var url = dataLs?.get(position)?.urlAddr.toString()
            GlideUtils.getInstance(container.context)?.displayImage(url, imageView!!)
            if(url.substring(url.lastIndexOf(".") + 1) == "mp4"){
                iv_video?.visibility = View.VISIBLE
            }
            var filename = url.substring(url.lastIndexOf("/") + 1)
            iv_video?.setOnClickListener{
                val attachDir = File(Constant.CACHE_DIR)
                var attachFile = File(attachDir.toString() + File.separator + "$filename")
                if(attachFile.exists()){
                    iv_video.visibility = View.GONE
                    video_view?.visibility = View.VISIBLE
                    mVideoView = video_view
                    mBtnVideo = iv_video
                    playVideo(video_view!!, attachFile)
                }else{
                    Toast.makeText(BaseApplication.instance, "文件下载中...", Toast.LENGTH_SHORT).show()
                }
            }
            return view!!
        }

        fun playVideo(videoView:VideoView,file:File){
            val mediaController = MediaController(videoView.context)
            videoView.setVideoPath(file.absolutePath)
            // 设置VideView与MediaController建立关联
            // 设置VideView与MediaController建立关联
            videoView.setMediaController(mediaController)
//        // 设置MediaController与VideView建立关联
            //        // 设置MediaController与VideView建立关联
            mediaController.setMediaPlayer(videoView)
            mediaController.visibility = View.INVISIBLE
            // 让VideoView获取焦点
//        mVideoView.requestFocus();
            // 让VideoView获取焦点
//        mVideoView.requestFocus();
            videoView.setOnPreparedListener(OnPreparedListener { mp: MediaPlayer ->

            })

            videoView.setOnCompletionListener(OnCompletionListener { mp: MediaPlayer? ->
//                mVideoView.setVideoPath(path);
                videoView.start()
            })

            videoView.setOnErrorListener(MediaPlayer.OnErrorListener { mp: MediaPlayer?, what: Int, extra: Int ->
                false
            })
            // 开始播放
            // 开始播放
            videoView.start()
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(`object` as View)
        }

        override fun isViewFromObject(view: View, `object`: Any): Boolean {
            return view == `object`
        }

        override fun getCount(): Int {
            if(dataLs == null){
                return 0
            }
            return dataLs!!.size
        }

    }
}